package com.heima.jopo.filter;

import com.heima.jopo.obj.UserInfo;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class AFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        System.out.println("进入session过滤器........");
        //父类转子类 强转
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取请求路径
        String reqUrl = request.getRequestURL().toString();
        String servletPath = request.getServletPath();
        //.endsWith()以什么结尾
        //判断路径是不是以什么结尾,  .css, .jsp, .gif , .js 不需要判断是否登录
        if (reqUrl.endsWith(".js") || reqUrl.endsWith(".jsp") || reqUrl.endsWith(".css") || reqUrl.endsWith(".jpg")) {
            filterChain.doFilter(request, response);
            return;
        }

        //servlet地址 包含：登录，注册，判断手机号是否存在接口 不需要判断是否登录
        List<String> pathList = new ArrayList<String>();
        pathList.add("/niubiservlet");
        pathList.add("/loginSer");
        pathList.add("/verify");


        //这两个地址不需要，判断是否登录
        if (pathList.contains(servletPath)) {
            filterChain.doFilter(request, response);
            return;
        }

        //获取session
        HttpSession session = request.getSession();
        List<UserInfo> listUser = (List<UserInfo>) session.getAttribute("seleUser");

        if (listUser == null) {
            //没有登录的用户去登录
            response.sendRedirect("html/login.jsp");
        }
        //登录了的继续执行
        filterChain.doFilter(request, response);

    }


    public void destroy() {

    }
}
